package com.fjnldx.mes.service.common;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fjnldx.mes.domain.domainReq.GetDataDicList;
import com.fjnldx.mes.domain.domainReq.QueryParamReq;
import com.fjnldx.mes.domain.domainRes.Result;
import com.fjnldx.mes.domain.domainRes.ResultObject;
import com.fjnldx.mes.domain.pojo.FzyDictionaryDataList;
import com.fjnldx.mes.domain.pojo.MesDinger;
import com.fjnldx.mes.domain.pojo.QueryParam;
import com.fjnldx.mes.domain.pojo.User;
import com.fjnldx.mes.mapper.common.CommonMapper;
import com.fjnldx.mes.mapper.dataDictionary.DataDictionaryMapper;
import com.fjnldx.mes.mapper.mes.MesDingErMapper;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class CommonService {
    @Resource
    CommonMapper commonMapper;
    @Resource
    DataDictionaryMapper dataDictionaryMapper;
    @Resource
    MesDingErMapper mesDingErMapper;
    @Resource
    UserMapper userMapper;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    public String getRole(String username) {
        return commonMapper.getRole(username);
    }

    public String getPassword(String username) {
        return commonMapper.getPassword(username);
    }

    public String getUserUuid(String username) {
        return commonMapper.getUserUuid(username);
    }
    public String getUserUuidKs(String username) {
        return commonMapper.getUserUuidKs(username);
    }

    public void updateUserUuid(String username, String uuid) {
        commonMapper.updateUserUuid(username, uuid);
    }

    /**
     * 用户注册
     *
     * @param user
     * @return
     */
    public Result userRegistration(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        List<User> users = userMapper.selectList(queryWrapper);
        if (users.size() > 0) {
            return Result.error("已存在该用户");
        }
        user.setRole("common");
        int i = userMapper.insert(user);
        return i > 0 ? Result.success("注册成功") : Result.error("系统异常");
    }

    /**
     * 修改密码
     *
     * @param user
     * @return
     */
    public Result changePassword(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        List<User> users = userMapper.selectList(queryWrapper);
        if (users.size() == 0) {
            return Result.error("不存在该用户，请先注册");
        }
        int i = userMapper.update(user, queryWrapper);
        return i > 0 ? Result.success("更新成功") : Result.error("系统异常");
    }

    /**
     * 查询对应工序品种
     *
     * @param gongxu
     * @return
     */
    public Result queryPzByGongXu(String gongxu) {
        QueryWrapper<MesDinger> wrapper = new QueryWrapper<>();
        wrapper.select("pz");
        wrapper.eq("gongxu", gongxu);
        List<MesDinger> res = mesDingErMapper.selectList(wrapper);
        ArrayList<String> arrayList = new ArrayList<>();
        for (MesDinger item : res) {
            arrayList.add(item.getPz());
        }
        return Result.success(arrayList);
    }

    /**
     * 图片上传-单张图片
     *
     * @return Result
     */
    public String uploadImage(MultipartFile file, HttpServletRequest request) {
        //获取网络协议
        String networkProtocol = request.getScheme();
        //网络IP
        String ip = request.getServerName();
        //端口号
        int port = request.getServerPort();
        String userDir = System.getProperty("user.dir");
        String uploadPath = userDir + "/images";
        File uploadDirectory = new File(uploadPath);
        if (uploadDirectory.exists()) {
            if (!uploadDirectory.isDirectory()) {
                uploadDirectory.delete();
            }
        } else {
            uploadDirectory.mkdir();
        }
        //这里可以支持多文件上传
        if (file != null) {
            try {
                String fileName = file.getOriginalFilename();
                //判断是否有文件且是否为图片文件
                if (fileName != null && !"".equalsIgnoreCase(fileName.trim()) && isImageFile(fileName)) {
                    String newFileName = UUID.randomUUID().toString() + getFileType(fileName);
                    //创建输出文件对象
                    File outFile = new File(uploadPath + "/" + newFileName);
                    //拷贝文件到输出文件对象
                    FileUtils.copyInputStreamToFile(file.getInputStream(), outFile);
                    return networkProtocol + "://" + ip + ":" + port + contextPath + "/OTA/" + newFileName;
                }
                return null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 获取文件后缀名
     *
     * @param fileName
     * @return
     */
    public String getFileType(String fileName) {
        if (fileName != null && fileName.contains(".")) {
            return fileName.substring(fileName.lastIndexOf("."));
        }
        return "";
    }

    /**
     * 是否为图片格式
     *
     * @param fileName
     * @return
     */
    public Boolean isImageFile(String fileName) {
        String[] img_type = new String[]{".jpg", ".jpeg", ".png", ".gif", ".bmp"};
        if (fileName == null) {
            return false;
        }
        fileName = fileName.toLowerCase();
        for (String type : img_type) {
            if (fileName.endsWith(type)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 测试测试
     */
    public Result test() throws Exception {
        try {
            List<Map<String, Object>> test = commonMapper.test();
            return Result.success(test);
        } catch (Exception e) {
            throw new Exception();
        }
    }

    /**
     * 顶部查询栏调用数据字典
     */
    public Result queryDataDictionaryList(GetDataDicList bh) throws Exception {
        try {
            List<FzyDictionaryDataList> list = dataDictionaryMapper.queryDataDictionaryList(new FzyDictionaryDataList(bh.getDic_bh(), -1));
            ResultObject<FzyDictionaryDataList> res = new ResultObject<>();
            res.setDataList(list);
            return Result.success(res);
        } catch (Exception e) {
            throw new Exception();
        }
    }

    /**
     * 查询参数值
     *
     * @param queryParamReq
     * @return
     */
    public Result queryParam(QueryParamReq queryParamReq) {
        List<QueryParam> queryParamList = commonMapper.queryParam(queryParamReq);
        return Result.success(queryParamList);
    }
}
